let toke = localStorage.getItem("token");
if (toke) {
  let unlogin = document.querySelector("#unlogin");
  unlogin.style.display = "none";
  let logined = document.querySelector("#logined");
  logined.style.display = "block";
}
/*
        1-购物车列表
        */
//快速点击变蓝
document.onselectstart = new Function("return false");
let cartArr = [];
//侧边栏
let num = document.querySelector(".navico-cartnum");
console.log(num);
async function loadCartList() {
  // 解构 出data属性
  let { data } = await myAxios.get(cartListAPI);
  cartArr = [...data.data];
  // console.log(cartArr);
  num.innerHTML = cartArr.length;

  // 根据数据 渲染列表
  renderList();
}

function renderList() {
  let liArr = cartArr.map((v) => {
    // let str = `<input type="checkbox" name="" id="" class="singleCK" onchange="singleCKChange(${v.pid},this)"/>`;
    // if (v.checked) {
    //   str = `<input type="checkbox" name="" id=""  checked  class="singleCK" onchange="singleCKChange(${v.pid},this)"/>`;
    // }
    console.log(v);
    return `
    <div class="mycart-item">
      <div class="mycart-item-tb">
        <div class="mycart-item-row cartlist clearfix">
          <div class="fl sp-1">
            <span class="goodscheck input-check" id="${v.product.id}" prices="${v.price}" amounts="${v.amount}" onclick="singleCK(this)"><i></i></span>
          </div>
          <div class="fl sp-2">
            <div class="mycart-item-img">
              <a href="./detail.html?id=${v.product.id}" target="_blank"
                ><img
                  src="http://192.168.18.95:1337${v.product.coverImage}"
                  alt="${v.product.name}"
              /></a>
            </div>
          </div>
          <div class="fl sp-3">
            <p class="mycart-item-name">
              <a href="./detail.html?id=${v.product.id}" target="_blank"
                >${v.product.name}</a
              >
            </p>
            <div class="mycart-item-tag">039900</div>
          </div>
          <div class="fl sp-4">
            <div class="mycart-item-sel disabled">
              <p>款式：标准版</p>
            </div>
          </div>
          <div class="fl sp-5">
            <p class="mycart-item-per">${v.product.price}.00元</p>
          </div>
          <div class="fl sp-6">
            <div class="mycart-item-count">
              <span class="num-minus btn_cart_list_buy_min" onclick="reduce(${
                v.id
              },this)">-</span>
              <input
                type="text" 
                class="inpt_cart_list_buy_num"
                value="${v.amount}"
                stock_num="312" readonly="readonly"
              />
              <span class="num-plus btn_cart_list_buy_plus" onclick="add(${
                v.id
              },this)">+</span>
            </div>
          </div>
          <div class="fl sp-7">
            <p class="mycart-item-price">${v.product.price * v.amount}.00元</p>
          </div>
          <div class="fl sp-8">
            <div class="mycart-item-tg">
              <a class="btn-del" href="javascript:;" onclick="delHandle(${
                v.id
              }, this)">删除</a>
              <a class="btn-fav" href="javascript:;">移入收藏夹</a>
            </div>
          </div>
        </div>
      </div>
    </div>
        `;
  });
  document.querySelector(".mycart-list").innerHTML = liArr.join("");
}

loadCartList();

//   2-删除   <button onclick="delHandle(${v.pid})">删除</button>
async function delHandle(pid, btn) {
  // console.log(pid);
  //调用删除接口-调用成功以后
  //页面变

  let res = await myAxios.delete(cartDeleteAPI + "/" + pid);
  // console.log(res);

  //1种-----删除数组的中元素-- renderlist或者删除 按钮所在的一行
  cartArr = cartArr.filter((v) => v.id != pid);
  // renderList()
  btn.parentNode.parentNode.parentNode.parentNode.parentNode.remove();
  reload();
  let mycartItem=document.querySelector(".mycart-item");
  if(!mycartItem){
    document.querySelector(".cartcheck").classList.remove("checked");
  }
  // 2种 直接loadCartList
  // loadCartList();
}

// 3-修改
// 修改的请求 ，修改成功以后 修改dom

function add(pid, btn) {
  console.log(pid, btn);

  // 获取 要修改的数字
  let pnumIpt = btn.parentNode.querySelector(".inpt_cart_list_buy_num");
  let pnum = parseInt(pnumIpt.value);
  pnum++;
  console.log(pnum);

  //数据中 对应的元素的pnum 修改 renderList
  let cartObj = cartArr.find((v) => v.id == pid);
  cartObj.amount = pnum;
  // renderList();
  pnumIpt.value = pnum;
  let list = btn.parentNode.parentNode.parentNode;
  let sumprice = list.querySelector(".sp-7 .mycart-item-price");
  console.log(sumprice);
  let oneprice = list.querySelector(".sp-5 .mycart-item-per");
  let oprice = parseFloat(oneprice.innerHTML);
  console.log(oprice);
  console.log(pnum);
  sumprice.innerHTML = oprice * pnum + ".00元";
  reload();
}
//减少
function reduce(pid, btn) {
  // 获取 要修改的数字
  let pnumIpt = btn.parentNode.querySelector(".inpt_cart_list_buy_num");
  let pnum = parseInt(pnumIpt.value);
  if (pnum == 1) {
    return;
  }
  pnum--;
  console.log(pnum);

  //数据中 对应的元素的pnum 修改 renderList
  let cartObj = cartArr.find((v) => v.id == pid);
  cartObj.amount = pnum;
  // renderList();
  pnumIpt.value = pnum;
  let list = btn.parentNode.parentNode.parentNode;
  let sumprice = list.querySelector(".sp-7 .mycart-item-price");
  console.log(sumprice);
  //单价
  let oneprice = list.querySelector(".sp-5 .mycart-item-per");
  let oprice = parseFloat(oneprice.innerHTML);
  console.log(oprice);
  console.log(pnum);
  sumprice.innerHTML = oprice * pnum + ".00元";
  reload();
}

//   全选
function allSelectChange(allCKipt) {
  if (allCKipt.classList.contains("checked")) {
    allCKipt.classList.remove("checked");
    document
      .querySelectorAll(".goodscheck")
      .forEach((v) => v.classList.remove("checked"));
  } else {
    allCKipt.classList.add("checked");

    // renderList();// 根据 数组元素的checked属性 来 渲染列表

    // 只重新修改所有ck的checked
    document
      .querySelectorAll(".goodscheck")
      .forEach((v) => v.classList.add("checked"));
  }
  reload();
}

// 单选-- 任意一个单选 发生改变 就得修改全局 ck的状态
function singleCK(ck) {
  // 任意的单选按钮状态改变-- 全选按钮的状态都可以变化
  if (ck.classList.contains("checked")) {
    ck.classList.remove("checked");
    document.querySelector(".cartcheck").classList.remove("checked");
  } else {
    ck.classList.add("checked");

    // renderList();// 根据 数组元素的checked属性 来 渲染列表
    let ipts = document.querySelectorAll(".goodscheck");
    let iptsArr = Array.from(ipts);

    let isAll = iptsArr.every((v) => v.classList.contains("checked") == true);
    if (isAll == true) {
      document.querySelector(".cartcheck").classList.add("checked");
    }
  }
  reload();
}
function reload() {
  let res = 0;
  let choices = document.querySelectorAll(".mycart-item-row .checked");
  let money = document.querySelector(".money");
  for (let i = 0; i < choices.length; i++) {
    let sums =
      choices[i].parentNode.parentNode.querySelector(
        ".mycart-item-price"
      ).innerHTML;
    sums = parseFloat(sums);
    // console.log(sums);
    res += sums;
    money.innerHTML = res + ".00元";
  }
  if (choices.length == 0) {
    money.innerHTML = 0 + ".00元";
  }
  let total = document.querySelector(".total");
  total.innerHTML = choices.length;
}

//去结算点击事件
let totalSum=document.querySelector(".mycart-tb-btn");
totalSum.onclick=function(){
let liArr=document.querySelectorAll(".mycart-item");
let idArr=[];
liArr.forEach(async function(v,i){
  let goodscheck=document.querySelectorAll(".goodscheck")[i];
  if (goodscheck.classList.contains("checked")){
    let product=goodscheck.id;
    idArr.push(product);
    let price=goodscheck.getAttribute("prices");
    console.log(price);
    let amount = document.querySelectorAll(".inpt_cart_list_buy_num")[i].value;
    let amounts=goodscheck.getAttribute("amounts");
    console.log(amounts);
    amount-=amounts;
    let res = await myAxios.post(cartAddAPI, {
      product,
      amount,
      price,
    });
    if(res.code==1){
      alert(res.msg);
    }
  }
})
location.href='../html/order.html?idArr='+idArr;

}